package com.example.Less.service.impl;

import com.example.Less.entity.PageResponse;
import com.example.Less.entity.Project;
import com.example.Less.entity.ProjectQuery;
import com.example.Less.repository.ProjectRepository;
import com.example.Less.service.ProjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ProjectServiceImpl implements ProjectService {
    
    private final ProjectRepository projectRepository;

    @Override
    public Project saveProject(Project project) {
        return projectRepository.save(project);
    }

    @Override
    public Project getProjectById(Integer id) {
        return projectRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Project not found"));
    }

    @Override
    public List<Project> getAllProjects() {
        return projectRepository.findAll();
    }

    @Override
    public Project updateProject(Project project) {
        if (!projectRepository.existsById(project.getId())) {
            throw new RuntimeException("Project not found");
        }
        return projectRepository.save(project);
    }

    @Override
    public void deleteProject(Integer id) {
        projectRepository.deleteById(id);
    }
    @Override
    public PageResponse<Project> searchProjects(ProjectQuery query) {
        Sort sort = buildSort(query.getOrderBy());
        Pageable pageable = PageRequest.of(query.getPageNum() - 1, query.getPageSize(), sort);

        Page<Project> page = projectRepository.searchProjects(
                query.getName(),
                query.getAddr(),
                query.getState(),
                query.getType(),
                query.getSort(),
                query.getIsDeleted(),
                query.getEnName(),
                pageable
        );

        return new PageResponse<>(
                page.getContent(),
                page.getTotalElements(),
                query.getPageNum(),
                query.getPageSize()
        );
    }
    /**
     * 构建排序对象
     */
    private Sort buildSort(String orderBy) {
        if (orderBy == null || orderBy.trim().isEmpty()) {
            return Sort.by(Sort.Direction.DESC, "createTime");
        }

        String[] parts = orderBy.split(" ");
        if (parts.length == 2) {
            Sort.Direction direction = parts[1].equalsIgnoreCase("asc") ?
                    Sort.Direction.ASC : Sort.Direction.DESC;
            return Sort.by(direction, parts[0]);
        }

        return Sort.by(Sort.Direction.DESC, "createTime");
    }
}